package com.factory.flutter_aq_factory

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlarmManager
import android.app.AlertDialog
import android.app.PendingIntent
import android.content.*
import android.content.pm.PackageManager
import android.content.res.AssetManager
import android.net.Uri
import android.os.*
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.util.Log
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.MethodCall;
import android.widget.EditText;
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.content.PermissionChecker
//import com.example.flutter_app2.FileUtil
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.EventChannel.EventSink
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.GeneratedPluginRegistrant
import java.io.File
import java.lang.Exception

class MainActivity: FlutterActivity() {

    private val CHANNEL = "qrscan"
    private val SCANACTION = "com.android.server.scannerservice.broadcast"
    //热更新
//    var asset: AssetManager? = null
//    var channel: MethodChannel? = null
//    lateinit var amOrigin: AssetManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        允许主进程发起http请求
//        if(android.os.Build.VERSION.SDK_INT > 9){
//            var policy:StrictMode.ThreadPolicy  = StrictMode.ThreadPolicy.Builder().permitAll().build()
//            StrictMode.setThreadPolicy(policy)
//        }
        //热更新
//        if (null == channel) {
//            channel = MethodChannel(flutterEngine?.dartExecutor, "com.test")
//            channel!!.setMethodCallHandler(object : MethodChannel.MethodCallHandler {
//                override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
//                    releaseSoAndResource()
//                    AlertDialog.Builder(this@MainActivity)
//                            .setMessage("更新完成，重启生效")
//                            .setCancelable(false)
//                            .setPositiveButton("确定", object: DialogInterface.OnClickListener{
//                                override fun onClick(dialog: DialogInterface?, which: Int) {
//                                    restartApp()
//                                }
//
//                            })
//                            .show()
//                }
//            })
//        }
        // 自动下载apk
        val channel = MethodChannel(flutterEngine?.dartExecutor, "install_apk_plugin")
        channel.setMethodCallHandler(object : MethodChannel.MethodCallHandler {
                override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
                    System.out.println(call.arguments)
                    val path = call.arguments as String
                    val file = File(path)
                    installApk(file, this@MainActivity)
                }
            })
        // 建立flutter监听发送事件
        EventChannel(flutterEngine!!.dartExecutor.binaryMessenger, CHANNEL).setStreamHandler(object : EventChannel.StreamHandler {
            private var chargingStateChangeReceiver: BroadcastReceiver? = null
            override fun onListen(arguments: Any?, events: EventSink?) {
                chargingStateChangeReceiver = createChargingStateChangeReceiver(events!!)
                val intentFilter = IntentFilter()
                intentFilter.addAction(SCANACTION)
                intentFilter.priority = Int.MAX_VALUE
                registerReceiver(
                        chargingStateChangeReceiver, intentFilter)
            }

            override fun onCancel(arguments: Any?) {
                unregisterReceiver(chargingStateChangeReceiver)
                chargingStateChangeReceiver = null
            }
        })

        // 建立flutter监听发送事件
//        EventChannel(flutterEngine!!.dartExecutor.binaryMessenger, "qrscanStatic").setStreamHandler(object : EventChannel.StreamHandler {
//            private var chargingStateChangeReceiver: BroadcastReceiver? = null
//            override fun onListen(arguments: Any?, events: EventSink?) {
//                chargingStateChangeReceiver = createChargingStateChangeReceiver(events!!)
//                val intentFilter = IntentFilter()
//                intentFilter.addAction(SCANACTION)
//                intentFilter.priority = Int.MAX_VALUE
//                registerReceiver(
//                        chargingStateChangeReceiver, intentFilter)
//            }
//
//            override fun onCancel(arguments: Any?) {
//                unregisterReceiver(chargingStateChangeReceiver)
//                chargingStateChangeReceiver = null
//            }
//        })
    }

    private fun installApk(apkFile: File, context: Context) {
        val installApkIntent = Intent()
        installApkIntent.action = Intent.ACTION_VIEW
        installApkIntent.addCategory(Intent.CATEGORY_DEFAULT)
        installApkIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        var apkUri: Uri? = null
        if (VERSION.SDK_INT > VERSION_CODES.M) {
            apkUri = FileProvider.getUriForFile(context, context.packageName + ".fileprovider", apkFile)
            installApkIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        } else {
            apkUri = Uri.fromFile(apkFile)
        }
        installApkIntent.setDataAndType(apkUri, "application/vnd.android.package-archive")
        if (context.packageManager.queryIntentActivities(installApkIntent, 0).size > 0) {
            context.startActivity(installApkIntent)
        }
    }

    private fun createChargingStateChangeReceiver(events:EventChannel.EventSink ):BroadcastReceiver {
        var broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                if (intent.action == "com.android.server.scannerservice.broadcast") {
                    var etCode: String?=intent.getStringExtra("scannerdata")
                    events.success(etCode!!.replace('\n',' ').trim())
                }
            }
        }
        return  broadcastReceiver;
    }

    //热更新
//    private fun releaseSoAndResource() {
//        FileUtil.copyFile(amOrigin,"app-release-1.apk", filesDir.absolutePath + "/app-release-1.apk")
//        FileUtil.copySo(filesDir.absolutePath + "/app-release-1.apk",
//                "lib/" + FileUtil.getArc(applicationInfo.nativeLibraryDir) + "/libapp.so",
//                filesDir.parentFile.absolutePath + "/lib/libapp1.so")
//        val sof = File(filesDir.parentFile.absolutePath + "/lib/libapp1.so")
//        sof.setExecutable(true)
//        sof.setReadable(true)
//    }
//
//    @SuppressLint("SoonBlockedPrivateApi")
//    override fun getAssets(): AssetManager {
//        if (null == asset && File(this.filesDir.absolutePath + "/app-release-1.apk").exists()) {
//
//            val info = packageManager.getPackageArchiveInfo(this.filesDir.absolutePath + "/app-release-1.apk", PackageManager.MATCH_UNINSTALLED_PACKAGES or PackageManager.GET_ACTIVITIES)!!.applicationInfo
//            info!!.publicSourceDir = this.filesDir.absolutePath + "/app-release-1.apk"
//            asset = packageManager.getResourcesForApplication(info).assets
//        }
//
//        if (!::amOrigin.isInitialized) {
//            amOrigin = super.getAssets()
//        }
//
//        return asset ?: amOrigin
//    }
//
//    private fun restartApp() {
//        val intent = baseContext.packageManager.getLaunchIntentForPackage(baseContext.packageName)
//        intent!!.putExtra("REBOOT", "reboot")
//        val restartIntent = PendingIntent.getActivity(applicationContext, 0, intent, PendingIntent.FLAG_ONE_SHOT)
//        val mgr = getSystemService(Context.ALARM_SERVICE) as AlarmManager
//        mgr[AlarmManager.RTC, System.currentTimeMillis() + 1000] = restartIntent
//        Process.killProcess(Process.myPid())
//    }


    /**
     * 移动端下载文件
     */
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "launchFile")
                .setMethodCallHandler { call: MethodCall, result: Result? ->
                    if (call.method == "viewPdf" || call.method == "viewExcel") {
                        val path = call.argument<String>("file_path")
                        if (!checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                            requestPermission(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE))
                        } else {
                            if (path != null) {
                                launchFile(path)
                            }
                        }
                    }
                }
    }
    private fun requestPermission(permission: Array<String>) {
        ActivityCompat.requestPermissions(this, permission, 1)
    }
    private fun checkPermission(permission: String): Boolean {
        return if (VERSION.SDK_INT < VERSION_CODES.M) {
            true
        } else {
            if (ContextCompat.checkSelfPermission(this, permission) == PermissionChecker.PERMISSION_GRANTED) {
                true
            } else {
                false
            }
        }
    }

    private fun launchFile(filePath: String) {
        val file = File(filePath)
        if (file.exists()) {
            val intent = Intent(Intent.ACTION_VIEW)
            intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
            intent.addCategory("android.intent.category.DEFAULT")
            var uri: Uri? = null
            uri = if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                val packageName = this.packageName
                FileProvider.getUriForFile(this, "$packageName.fileProvider", File(filePath))
            } else {
                Uri.fromFile(file)
            }
            if (filePath.contains(".pdf")) intent.setDataAndType(uri, "application/pdf") else intent.setDataAndType(uri, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            try {
                this.startActivity(intent)
            } catch (e: Exception) {
                //Could not launch the file.
            }
        }
    }

}
